<!DOCTYPE html><html lang="[&quot;zh-Hans&quot;,&quot;zh-CN&quot;,&quot;default&quot;]"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"><meta name="description" content="React-新特性Hooks"><meta name="keywords" content="hooks,react"><meta name="author" content="wenmu"><meta name="copyright" content="wenmu"><title>React-新特性Hooks | 温木的博客</title><link rel="shortcut icon" href="/melody-favicon.ico"><link rel="stylesheet" href="/css/index.css?version=1.6.1"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@latest/css/font-awesome.min.css?version=1.6.1"><link rel="dns-prefetch" href="https://cdn.staticfile.org"><link rel="dns-prefetch" href="https://cdn.bootcss.com"><link rel="dns-prefetch" href="https://creativecommons.org"><link rel="dns-prefetch" href="http://ta.qq.com"><script>(function() {
   var hm = document.createElement("script");
   hm.src = "https://tajs.qq.com/stats?sId=&lt;script type=&quot;text/javascript&quot; src=&quot;http://tajs.qq.com/stats?sId=66523541&quot; charset=&quot;UTF-8&quot;&gt;&lt;/script&gt;";
   var s = document.getElementsByTagName("script")[0];
   s.parentNode.insertBefore(hm, s);
 })();</script><script>var GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  }
} </script><meta name="generator" content="Hexo 4.2.0"></head><body><i class="fa fa-arrow-right" id="toggle-sidebar" aria-hidden="true"></i><div id="sidebar"><div class="toggle-sidebar-info text-center"><span data-toggle="切换文章详情">切换站点概览</span><hr></div><div class="sidebar-toc"><div class="sidebar-toc__title">目录</div><div class="sidebar-toc__progress"><span class="progress-notice">你已经读了</span><span class="progress-num">0</span><span class="progress-percentage">%</span><div class="sidebar-toc__progress-bar"></div></div><div class="sidebar-toc__content"><ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#Hook-解决的问题"><span class="toc-number">1.</span> <span class="toc-text">Hook 解决的问题</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#副作用"><span class="toc-number">2.</span> <span class="toc-text">副作用</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#useState-使用函数初始化"><span class="toc-number">3.</span> <span class="toc-text">useState 使用函数初始化</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#class-中的-setState-和-useState-更新-state-的区别"><span class="toc-number">4.</span> <span class="toc-text">class 中的 setState 和 useState 更新 state 的区别</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#ContextHook"><span class="toc-number">5.</span> <span class="toc-text">ContextHook</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#memoHook"><span class="toc-number">6.</span> <span class="toc-text">memoHook</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#effect-hook"><span class="toc-number">7.</span> <span class="toc-text">effect hook</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#dd"><span class="toc-number">8.</span> <span class="toc-text">dd</span></a></li></ol></div></div><div class="author-info hide"><div class="author-info__avatar text-center"><img src="https://i.loli.net/2020/02/27/xwaBoOj158MfNyq.jpg"></div><div class="author-info__name text-center">wenmu</div><div class="author-info__description text-center">记录一些在工作中或学习新知识时学到的一些知识点；正所谓好记性不如一个烂笔头，温故而知新！</div><hr><div class="author-info-articles"><a class="author-info-articles__archives article-meta" href="/archives"><span class="pull-left">文章</span><span class="pull-right">115</span></a><a class="author-info-articles__tags article-meta" href="/tags"><span class="pull-left">标签</span><span class="pull-right">52</span></a><a class="author-info-articles__categories article-meta" href="/categories"><span class="pull-left">分类</span><span class="pull-right">30</span></a></div></div></div><div id="content-outer"><div class="no-bg" id="top-container"><div id="page-header"><span class="pull-left"> <a id="site-name" href="/">温木的博客</a></span><i class="fa fa-bars toggle-menu pull-right" aria-hidden="true"></i><span class="pull-right menus"><a class="site-page" href="/">首页</a><a class="site-page" href="/archives">文章</a><a class="site-page" href="/tags">标签</a><a class="site-page" href="/categories">分类</a></span></div><div id="post-info"><div id="post-title">React-新特性Hooks</div><div id="post-meta"><time class="post-meta__date"><i class="fa fa-calendar" aria-hidden="true"></i> 2020-01-09</time><span class="post-meta__separator">|</span><i class="fa fa-inbox post-meta__icon" aria-hidden="true"></i><a class="post-meta__categories" href="/categories/react/">react</a></div></div></div><div class="layout" id="content-inner"><article id="post"><div class="article-container" id="post-content"><h3 id="Hook-解决的问题"><a href="#Hook-解决的问题" class="headerlink" title="Hook 解决的问题"></a>Hook 解决的问题</h3><ul>
<li>state 共享重用(useState)</li>
<li>class 中生命周期函数经常包含不相关的逻辑，但又把相关逻辑分离到了几个不同方法中的问题(useEffect)</li>
</ul>
<h3 id="副作用"><a href="#副作用" class="headerlink" title="副作用"></a>副作用</h3><p>在前端开发中，经常会听到副作用的这个说法，很多人以为和吃药有副作用是一个意思，其实不是，前端的主要作用就是 data 到 UI 的渲染，所以这里说的副作用就是除了 data 渲染成 UI 以为的其他操作都算是副作用。比如事件绑定，获取数据等等。</p>
<a id="more"></a>

<hr>
<p>useState 是有顺序要求的，并且每次调用，需要调用所有声明过的 useState。</p>
<blockquote>
<p>也就是说：调用时，必须按照已有的顺序和数量进行调用。 ###如何避免少调用了 useState<br>可以通过<code>eslint-plugin-react-hooks</code>来帮助检验。</p>
</blockquote>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm i -D eslint-plugin-react-hooks</span><br></pre></td></tr></table></figure>

<p>在 package.json 中增加配置,在顶级增加如下：</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">"eslintConfig": &#123;</span><br><span class="line">    "extends": "react-app",</span><br><span class="line">    "plugins": [</span><br><span class="line">      <span class="string">"react-hooks"</span></span><br><span class="line">    ],</span><br><span class="line">    "rules": &#123;</span><br><span class="line">      "react-hooks/rules-of-hooks": "error"</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br></pre></td></tr></table></figure>

<p>这样有地方写的不符合规则，就会报错。</p>
<h3 id="useState-使用函数初始化"><a href="#useState-使用函数初始化" class="headerlink" title="useState 使用函数初始化"></a>useState 使用函数初始化</h3><p>有时候，我们需要根据条件去初始化 state，如果先计算好条件，然后在把结果传递给 useState，这样会使计算过程每次渲染都会执行，然而只有第一次初始化是需要用到这些条件判断的，以后的每次执行都是浪费，如下</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">App</span>(<span class="params">props</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> defaultCount = props.defaultCount || <span class="number">0</span>;</span><br><span class="line">  <span class="keyword">const</span> [count, setCount] = useState(defaultCount);</span><br></pre></td></tr></table></figure>

<p>只有第一次从 props 中获取 defaultCount 是有用的，以后的每次渲染这样代码照样执行，但是是没有价值的。<br>可以给 useState 传递函数来初始化，函数的返回值就是默认值。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">App</span>(<span class="params">props</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> [count, setCount] = useState(<span class="function"><span class="params">()</span> =&gt;</span> props.defaultCount || <span class="number">0</span>);</span><br></pre></td></tr></table></figure>

<blockquote>
<p>每次 state 的改变 App 函数都会执行，react 是如何知道每次的调用是不是第一次？<br>useState 的内部机制做了处理。并且在 state 没发生改变的时候，是不会引起新的渲染的。</p>
</blockquote>
<h3 id="class-中的-setState-和-useState-更新-state-的区别"><a href="#class-中的-setState-和-useState-更新-state-的区别" class="headerlink" title="class 中的 setState 和 useState 更新 state 的区别"></a>class 中的 setState 和 useState 更新 state 的区别</h3><ul>
<li>class 组件中的 setState 是用更新的属性和原来的 state 进行合并，然后再更新。</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">this</span>.state = &#123;</span><br><span class="line">  name: <span class="string">"zhangsan"</span>,</span><br><span class="line">  age: <span class="number">29</span>,</span><br><span class="line">&#125;;</span><br><span class="line"><span class="comment">// ....</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">this</span>.setState(&#123; <span class="attr">name</span>: <span class="string">"lisi"</span> &#125;);</span><br></pre></td></tr></table></figure>

<p>当通过 setState 只更改 name 时，age 也不会丢失，react 会先用现在发生变化的 state 和原来的 state 进行合并，然后再更新。</p>
<ul>
<li>useState 更新 state 是替换原来的 state。</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> [person, setPerson] = useState(&#123; <span class="attr">name</span>: <span class="string">"zhagnsan"</span>, <span class="attr">age</span>: <span class="number">20</span> &#125;);</span><br><span class="line"><span class="comment">//....</span></span><br><span class="line">setPerson(&#123; <span class="attr">name</span>: <span class="string">"lisi"</span> &#125;);</span><br></pre></td></tr></table></figure>

<p>通过上面的更新，原来的 person 会被替换，age 属性丢失了。</p>
<h3 id="ContextHook"><a href="#ContextHook" class="headerlink" title="ContextHook"></a>ContextHook</h3><p>我们可以通过 Consumer 获取 context 的值，但是每次声明 Consumer 很麻烦，所以有了静态的 contextType,但是 contextType 每个组件只能有一个，如果声明多个，最后一个有效。<br>使用 contexthook 可以轻松解决上面的问题。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> count = useContext(CountContext);</span><br><span class="line"><span class="keyword">const</span> name = useContext(NameContext);</span><br></pre></td></tr></table></figure>

<h3 id="memoHook"><a href="#memoHook" class="headerlink" title="memoHook"></a>memoHook</h3><p><a href="https://zh-hans.reactjs.org/docs/hooks-reference.html#usememo" target="_blank" rel="noopener">官网解释</a></p>
<p>useMemo<br>把“创建”函数和依赖项数组作为参数传入 useMemo，它仅会在某个依赖项改变时才重新计算 。</p>
<blockquote>
<p>注意：只要是依赖项改变，就会重新计算。（有时候不要被设置的布尔值给迷惑了）</p>
</blockquote>
<p>如果只需要 useMemo 计算一次，第二个参数传空数组即可。<br>useMemo 也可以用于返回一个函数，如果返回的是函数，则可以直接使用 useCallback.第二个参数如果是空数组，则 useCallback 则会只生成的一次函数，即使返回的是箭头函数，也不影响。</p>
<h3 id="effect-hook"><a href="#effect-hook" class="headerlink" title="effect hook"></a>effect hook</h3><p>React 将按照 effect 声明的顺序依次调用组件中的<em>每一个</em> effect。<br>effect 每次调用都会用一个新的函数，生成一个新的 effect，所以每次调用之前都会清楚之前的。</p>
<h3 id="dd"><a href="#dd" class="headerlink" title="dd"></a>dd</h3><p><a href="https://zh-hans.reactjs.org/docs/hooks-effect.html#explanation-why-effects-run-on-each-update" target="_blank" rel="noopener">官网解释</a></p>
</div></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">wenmu</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://blog.wangpengpeng.site/2020/01/09/React-%E6%96%B0%E7%89%B9%E6%80%A7Hooks/">http://blog.wangpengpeng.site/2020/01/09/React-%E6%96%B0%E7%89%B9%E6%80%A7Hooks/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank" rel="noopener">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://blog.wangpengpeng.site">温木的博客</a>！</span></div></div><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/hooks/">hooks</a><a class="post-meta__tags" href="/tags/react/">react</a></div><div class="post-qr-code"><div class="post-qr-code-item"><img class="post-qr-code__img" src="https://i.loli.net/2020/02/27/hOBzIxFDJMCrmtN.jpg"><div class="post-qr-code__desc">微信打赏</div></div></div><nav id="pagination"><div class="prev-post pull-left"><a href="/2020/01/09/Nextjs+React+KOA-2/"><i class="fa fa-chevron-left">  </i><span>Nextjs+React+KOA-2</span></a></div><div class="next-post pull-right"><a href="/2020/01/09/PWA%E7%AC%94%E8%AE%B0/"><span>PWA笔记</span><i class="fa fa-chevron-right"></i></a></div></nav><div id="vcomment"></div><script src="https://cdn1.lncld.net/static/js/3.0.4/av-min.js"></script><script src="https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js"></script><script>var notify = 'false' == true ? true : false;
var verify = 'false' == true ? true : false;
var GUEST_INFO = ['nick','mail','link'];
var guest_info = 'nick,mail,link'.split(',').filter(function(item){
  return GUEST_INFO.indexOf(item) > -1
});
guest_info = guest_info.length == 0 ? GUEST_INFO :guest_info;
window.valine = new Valine({
  el:'#vcomment',
  notify:notify,
  verify:verify,
  appId:'U1QqpeQNuBnRsfygHk1GQ30q-gzGzoHsz',
  appKey:'dunDQzEseDzgsKgw4qLQcog1',
  placeholder:'支持markdown！',
  avatar:'wavatar',
  guest_info:guest_info,
  pageSize:'20',
  lang: 'zh-cn'
})</script></div></div><footer><div class="layout" id="footer"><div class="copyright">&copy;2019 - 2020 By wenmu</div><div class="framework-info"><span>驱动 - </span><a href="http://hexo.io" target="_blank" rel="noopener"><span>Hexo</span></a><span class="footer-separator">|</span><span>主题 - </span><a href="https://github.com/Molunerfinn/hexo-theme-melody" target="_blank" rel="noopener"><span>Melody</span></a></div><div class="busuanzi"><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><span id="busuanzi_container_page_pv">该文访问量<span id="busuanzi_value_page_pv"></span><span></span></span></div></div></footer><i class="fa fa-arrow-up" id="go-up" aria-hidden="true"></i><script src="https://cdn.jsdelivr.net/npm/animejs@latest/anime.min.js"></script><script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-animate@latest/velocity.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-ui-pack@latest/velocity.ui.min.js"></script><script src="/js/utils.js?version=1.6.1"></script><script src="/js/fancybox.js?version=1.6.1"></script><script src="/js/sidebar.js?version=1.6.1"></script><script src="/js/copy.js?version=1.6.1"></script><script src="/js/fireworks.js?version=1.6.1"></script><script src="/js/transition.js?version=1.6.1"></script><script src="/js/scroll.js?version=1.6.1"></script><script src="/js/head.js?version=1.6.1"></script><script>if(/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
  $('#nav').addClass('is-mobile')
  $('footer').addClass('is-mobile')
}</script></body></html>